package com.zsj.queue;


import java.util.*;

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2024/3/24 12:40
 * @Description 利用队列解决一些算法问题
 */
public class Question {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                new TreeNode(2,
                        new TreeNode(4),
                        new TreeNode(5)),
                new TreeNode(3,
                        new TreeNode(6),
                        new TreeNode(7)));
        levelOrder(root);

    }

    //二叉树 层序遍历  dfs
    public static List<List<Integer>> levelOrder(TreeNode root) {
//        Queue<TreeNode> linkedListQueue = new ArrayDeque<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        LinkedListQueue<TreeNode> linkedListQueue = new LinkedListQueue<>();
        linkedListQueue.offer(root);
        int c = 1;//当前每一层的数量 默认从根节点开始只有一层
        while (!linkedListQueue.isEmpty()) {
            //和我刚想的一样 这里加一个内层循环 每次都把队列中所有元素取出来就是一层
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < c; i++) {
                TreeNode first = linkedListQueue.poll();
                temp.add(first.val);
                if (first.left != null) linkedListQueue.offer(first.left);
                if (first.right != null) linkedListQueue.offer(first.right);
            }
            c = linkedListQueue.size();//获取到当前队列中的数量
            result.add(temp);
        }
        return result;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
